﻿using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;

namespace WebApiSecurity.Tests
{
    [TestFixture]
    public class Step04
    {
        [Test]
        public async Task Can_call_the_api()
        {
            var client = new HttpClient(new AuthenticationHandler()) {BaseAddress = new Uri("http://localhost.fiddler:49623/")};
            var response = await client.GetAsync("api/values");
            var result = await response.Content.ReadAsAsync<string[]>();

            foreach (var value in result) Console.WriteLine(value);
        }

        public class AuthenticationHandler : DelegatingHandler
        {
            public AuthenticationHandler() : base(new HttpClientHandler())
            {
            }

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                request.Headers.Add("Demo-Key", "920ab4e7-27cf-4236-99b2-7538ce11c28e");
                request.Headers.Add("Demo-Signature", ComputeSignature("920ab4e7-27cf-4236-99b2-7538ce11c28e", "K+bGN6OgfGN4O6Wrj8SRJK//PO4I1QsQNlFHC5pYvsE="));
                return base.SendAsync(request, cancellationToken);
            }

            private string ComputeSignature(string accessKey, string accessKeySecret)
            {
                using (var hmac = new HMACSHA256(Convert.FromBase64String(accessKeySecret)))
                    return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(accessKey)));
            }
        }
    }
}
